
const router = require('koa-router')()

//用户管理列表
router.get('/getwuliu',async(ctx,next)=>{
    let sql = 'select * from wuliu'
    let res = await ctx.db.query(sql)
    // let filename = path.join(__dirname,"../public/users.json")
    // let data = fs.readFileSync(filename)
    // let res = JSON.parse(data)
  
    ctx.body = {'code':200,'msg':res}
  
  })
  
  //搜索
  router.post('/search',async(ctx,next)=>{
    let key = ctx.request.body.key
    console.log(key);
    let sql = "select * from wuliu where name like concat('%',?,'%') || lutu like concat('%',?,'%')"
    let res = await ctx.db.query(sql,[key,key])
    console.log(res);
    ctx.body = {'code':200,'msg':res}
  })

  //更新数据
  router.post('/updatawuliu',async(ctx,next)=>{
    let row = ctx.request.body
    row.edit = false
    console.log(row)
    let sql = 'update wuliu set name=?,lutu=?,phone=?,address=? where id=?'
    await ctx.db.query(sql,[row.name,row.lutu,row.phone,row.address,row.id])
    // let filename = path.join(__dirname,"../public/users.json")
    // let data =  fs.readFileSync(filename)
    // let res = JSON.parse(data)
    // //根据id找到索引
    // let index = res.findIndex(item=>item.id==row.id)
    // //从索引开始删除一条数据，并把row加入进去，即替换
    // res.splice(index,1,row)
    // fs.writeFileSync(filename,JSON.stringify(res))
    ctx.body={'code':200,"msg":"编辑成功"}
  
  })
  
  //添加用户数据
  router.post('/addwuliu', async(ctx,next)=>{
    let row = ctx.request.body
    console.log(row);
    let sql = 'insert into wuliu(name,lutu,address,phone) values(?,?,?,?)'
    await ctx.db.query(sql,[row.name,row.lutu,row.address,row.phone])
    // let filename = path.join(__dirname,"../public/users.json")
    // let data = fs.readFileSync(filename)
    // let res = JSON.parse(data)
    // //把新数据放进去 
    // if(res.length!==0){
    //   var id = res[res.length-1].id +1 //id为数组中最后一个数据的id+1
    // }else{
    //   id = 0
    // }
    // row.id = id
    // row.edit = false
    // res.push(row)
    // fs.writeFileSync(filename, JSON.stringify(res))
    ctx.body={'code':200,'msg':"添加成功"}
  
  })
  
  
  //删除某个用户数据
  router.post('/deletewuliu',async(ctx,next)=>{
    let id = ctx.request.body.id
    let sql='delete from wuliu where id=?'
    await ctx.db.query(sql,[id])
    // let filename = path.join(__dirname,"../public/users.json")
    // let data = fs.readFileSync(filename)
    // let res = JSON.parse(data)
    // //根据条件删除一项
    // let result = res.filter(item=>{
    //   return item.id!==id
    // })
    // //把剩余的数据存储
    // fs.writeFileSync(filename,JSON.stringify(result))
    ctx.body={"code":200,"msg":'删除成功'}
  })

  module.exports = router